package com.dingpeikeji.quickdeer.modules.applycargo.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.beanvalidator.BeanValidators;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.modules.applycargo.entity.TApplycargo;
import com.dingpeikeji.quickdeer.modules.applycargo.service.TApplycargoService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.google.common.collect.Lists;

/**
 * 客运公司车辆加盟Controller
 */
@Controller
@RequestMapping("/f/applycargo")
public class FApplycargoController extends BaseController {

	@Autowired
	private TApplycargoService tApplycargoService;
	
	@RequestMapping(value = "form")
	public String form(TApplycargo tApplycargo, Model model) {
		model.addAttribute("tApplycargo", tApplycargo);
		return "modules/applycargo/fApplycargoForm";
	}

	@RequestMapping(value = "save")
	public String save(TApplycargo tApplycargo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		List<String> messages = Lists.newArrayList();
		try{
			BeanValidators.validateWithException(validator, tApplycargo);
		}catch(ConstraintViolationException ex){
			List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
			messages.addAll(list);
		}
		String contactstel = tApplycargo.getContactstel();
		String email = tApplycargo.getEmail();
		if(!ValidateTool.isMobile(contactstel) &&
				!ValidateTool.isPhone(contactstel)) {
			messages.add("联系电话填写不正确");
		}
		if(!ValidateTool.isEmail(email)) {
			messages.add("联系邮箱填写不正确");
		}
		if(messages.isEmpty()) {
			tApplycargo.setAuditstatus(TApplycargo.AUDITSTATUS_NEW);
			tApplycargoService.save(tApplycargo);
			//addMessage(redirectAttributes, "申请客运公司车辆加盟成功");
			request.getSession().setAttribute("mes","您已提交成功，相关负责人稍后将联系您，请保持电话畅通");
			return "redirect:/webInfo.jsp?id=jm";
		} else {
			request.getSession().setAttribute("mes", messages.get(0));
			String form = form(tApplycargo, model);
			return "redirect:/webInfo.jsp?id=jm";
		}
	}

}